package cn.com.dstz.taglib;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import cn.com.dstz.utils.RequestUtils;
import cn.com.dstz.web.constants.Constants;

public class PermissionsFilter extends TagSupport{
	
	private static final long serialVersionUID = 1L;
	
	public String url;
	public String name;
	public String target;
	public Boolean isparent;
	
	@Override
	public int doEndTag( ) throws JspException {
		 return EVAL_PAGE;
	}


	@Override
	public int doStartTag( ) throws JspException {
		
		HttpSession session = pageContext.getSession( );
		
		List< Map< String, Object >> purviewList = RequestUtils.getEntityInSession( Constants.ADMIN_PURVIEW,  session ); // 获取权限列表
		
		for( Map< String, Object > purview : purviewList ){
			Object url = purview.get( "url" );
			
			Integer parentid = ( Integer )purview.get( "parentid" );
			if( isparent ){
				if( parentid > 0 ){
					continue;
				}
			}else{
				if( parentid == 0 ){
					continue;
				}
			}
			
			if( StringUtils.equals( url.toString( ), this.url )){
				JspWriter out = this.pageContext.getOut( );
				try{
					out.print( responseURL( purview ) );
				}catch( IOException e ){
					e.printStackTrace();
				}
			}
		}
		return SKIP_BODY;
	}


	@Override
	public void release( ) {
		super.release( );
		url = null;
		name = null;
		target = null;
		isparent = null;
	}
	
	public String getHref( Map< String, Object > purview ){
		return "<a href=\"" + getUrlWithServletContextPath( )+ "\" target=\"" + getTarget( ) + "\">" + ( StringUtils.isNotBlank( name ) ? name : purview.get( "name" )) + "</a>";
		
	}
	public String responseURL( Map< String, Object > purview ){
		return "<li class=\"menuItem\" >" + getHref( purview )+ "</li>" ;
	}


	public String getUrlWithServletContextPath( ){
		return this.pageContext.getServletContext( ).getContextPath( ) + url;
	}
	
	
	public String getUrl( ) {
		return url;
	}
	
	public void setUrl( String url ) {
		this.url = url;
	}
	
	public String getName( ) {
		return name;
	}
	
	public void setName( String name ) {
		this.name = name;
	}
	
	public String getTarget( ) {
		if( StringUtils.isBlank( target ) ){
			target = "rightFrame";
		}
		return target;
	}
	
	public void setTarget( String target ) {
		this.target = target;
	}
	
	public Boolean getIsparent( ) {
		return isparent;
	}
	
	public void setIsparent( Boolean isparent ) {
		this.isparent = isparent;
	}
	
	

}
